/*
 * Copyright (c) 2009, Magnus Robertsson. All Rights Reserved.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 *
 */

package se.jayway.javafxbinder.util;


/**
 * Representation of a class file. A class file has a name and contains bytecode.
 * 
 * @author Magnus Robertsson
 */
public abstract class ClassFile {
	private final String name;
	private final ClassPath classPath;

	/**
	 * Creates a ClassFile from a fully qualified name separated by dot
	 * characters, e.g. "java.lang.String".
	 * 
	 * @param name A fully qualified Java class name.
	 */
	protected ClassFile(String name, ClassPath classPath) {
		this.name = name;
		this.classPath = classPath;
	}

	public String getClassName() {
		return name;
	}
	
	public Class<?> loadClass() throws ClassNotFoundException {
		return classPath.getClassLoader().loadClass(name);
	}
	
	public String getPackage() {
		int index = name.lastIndexOf('.');
		if (index == -1) {
			return "";
		} else {
			return name.substring(0, index);
		}
	}
	
	public boolean isAnonymousClass() {
		try {
			return loadClass().isAnonymousClass();
		} catch (ClassNotFoundException e) {
			throw new IllegalStateException("Could not determine if "
					+ name
					+ " is anonymous since it couldn't be found", e);
		}
	}

	public boolean isMemberClass() {
		try {
			return loadClass().isMemberClass();
		} catch (ClassNotFoundException e) {
			throw new IllegalStateException("Could not determine if "
					+ name
					+ " is local since it couldn't be found", e);
		}
	}
}
